package yunwo.cn.yzstation.printer;

import android.content.Context;
import android.util.Log;


import java.util.Arrays;

import yunwo.cn.yzstation.bean.printBean.PrintLabelBean;
import yunwo.cn.yzstation.bean.printBean.PrintTicketBean;
import yunwo.cn.yzstation.utils.MoneyUtils;
import zpSDK.zpSDK.zpBluetoothPrinter;


/**
 * Created by gpayne on 2017/9/5.
 */

public class YH423PrintUtils {
    private Context mContext;
    private static YH423PrintUtils printer;
    public zpBluetoothPrinter zpSDK;

    private YH423PrintUtils(Context mContext) {
        this.mContext = mContext;
        zpSDK = new zpBluetoothPrinter(mContext);
    }

    public static YH423PrintUtils getInstance(Context context){
        if (printer == null){
            printer = new YH423PrintUtils(context);
        }
        return printer;
    }

    public void printLabel(String address, PrintLabelBean labelBean, int cout){
        zpSDK.connect(address);
        int width = 568;
        int total = 0; //51.8  72
        zpSDK.pageSetup(width,350);
        zpSDK.drawBox(1,0,0,width,350);
        zpSDK.drawText(10,total+15,empty2Default(labelBean.getGroupName(),"云企集团"),4,0,1,false,false);
        zpSDK.drawText(200, total+30, (int) (width*0.667-100), 80, empty2Default(labelBean.getCompanyName(),""), 2,0, 0, false, false);
        zpSDK.drawText(width*2/3+5,total+5,"运单号",2,0,0,false,false);

        String s = "";
        if (labelBean.getGnd() == 0 || labelBean.getGnd() == 0.0) {
            s= "";
        }else {
            s = "-";
        }
        zpSDK.drawText(width*2/3+10,total+35,empty2Default(labelBean.getTrackNumber(),"")+s+ String.format(type(labelBean.getGnd()),cout),2,0,0,false,false);
        Log.d("vvvvvv", "2222222");
        total += 70;
        zpSDK.drawLine(1,(int) (width*0.667),total-70, (int) (width*0.667),total,true);
        zpSDK.drawLine(1,0,total,width,total,true);

        String startCity = empty2Default(labelBean.getStartCity(),"");

        zpSDK.drawText(20,total+20,startCity+" → "+empty2Default(labelBean.getEndCity(),""),3,0,1,false,false);

        zpSDK.drawLine(1,width * 3/4,total,width * 3/4,total+70,true);
        zpSDK.drawText(width*3/4+5,total+5,"中转站",2,0,0,false,false);
        zpSDK.drawText(width*3/4+25,total+30,empty2Default(labelBean.getTransStation(),""),3,0,1,false,false);

        total+=70;
        zpSDK.drawLine(1,0,total,width,total,true);
//
        zpSDK.drawLine(1,width/2,total,width/2,total+80,true);
        zpSDK.drawLine(1,width/2+width/5,total,width/2+width/5,total+80,true);
//
        zpSDK.drawText(10,total+10,"收货人",2,0,0,false,false);
        zpSDK.drawText(20,total+39,empty2Default(labelBean.getUserName(),""),3,0,0,false,false);
//
        zpSDK.drawText(width/2+10,total+10,"配送方式",2,0,0,false,false);
        zpSDK.drawText(width/2+20,total+39,empty2Default(labelBean.getSendMethod(),""),2,0,0,false,false);

        zpSDK.drawText(width/2+width/5+10,total+10,"件数："+ String.format("%d/%s",cout,empty2Default(labelBean.getNumber(),"1")),2,0,0,false,false);
        zpSDK.drawText(width/2+width/5+10,total+44,"品名："+empty2Default(labelBean.getProductName(),""),2,0,0,false,false);
//
        Log.d("vvvvvv", "333333333");
        total+=80;
        zpSDK.drawLine(1,0,total,width,total,true);
//
        zpSDK.drawText(width/4,total+5,empty2Default(labelBean.getSendPersonName(),"")+" "+empty2Default(labelBean.getTime(),""),2,0,0,false,false);

        String s1;
        if (labelBean.getGnd()>0) {
            s1= "-";
        }else {
            s1 = "_";
        }
        zpSDK.drawBarCode(30,total+35,empty2Default(labelBean.getTrackNumber(),"")+s1+ String.format(type(labelBean.getGnd()),cout), 128,false,3,70);

        zpSDK.print(0,1);
        zpSDK.disconnect();

        Log.d("vvvvvv", "444444");
    }

    public void printTicket(String address, PrintTicketBean ticketBean){
        /*boolean connected = zpSDK.isConnected();
        if (connected) {
            zpSDK.disconnect();
        }*/
        zpSDK.connect(address);
        Log.d("vvvvvv", "555555");
        int total = 0;
        int width = 568;

        total += 30;

        zpSDK.pageSetup(width,pageHeight(ticketBean));
        zpSDK.drawText(20,total,
                empty2Default(ticketBean.getGroupName(),"云企集团"),
                5,0,1,false,false);
        zpSDK.drawText(50,total+50+10,
                "-" + empty2Default(ticketBean.getCompanyName(),"")+"-"
                ,2,0,0,false,false);

//        zpSDK.drawGraphic(width*3/5+30,total,50,50,BitmapFactory.decodeResource(mContext.getResources(),R.mipmap.icon_dan));
        zpSDK.drawText(width/2,total+30,"运单号："+empty2Default(ticketBean.getTrackNumber(),""),2,0,0,false,false);
        if (empty2Default(ticketBean.getSelfCodeNumber(),"").length() > 0) {
            zpSDK.drawText(width/2, total+30+24+10, "自编号：" + empty2Default(ticketBean.getSelfCodeNumber(), ""), 2, 0, 0, false, false);
        }
        total += 96;
        zpSDK.drawLine(1,0,total,width,total,true);
        String left = empty2Default(ticketBean.getStartCity(),"");
        String right = empty2Default(ticketBean.getEndCity(),"");
        int leftL = left.length() * 48;
        int rightL = right.length() * 48;
        int centerL = 110;
        Log.d("vvvvvv", "66666666");
        int leftStart = (width - leftL - rightL - centerL)/2;

        zpSDK.drawText(leftStart,total+10,left,4,0,1,false,false);
        zpSDK.drawText(leftStart + leftL + centerL,total+10,right,4,0,1,false,false);
        zpSDK.drawText(leftStart+leftL+20,total,"→",6,0,1,false,false);

        total +=68;
        zpSDK.drawLine(1,0,total,width,total,true);
        total += 10;
        int lineHeight = 34;
        int lines = 0;

        zpSDK.drawText(10,total+lineHeight*lines,"收货人：" +
                empty2Default(ticketBean.getUserName(),"")+" "+
                empty2Default(ticketBean.getUserPhone(),""),2,0,0,false,false);

        lines++;
        zpSDK.drawText(10,total+lineHeight*lines,"收货地址："+empty2Default(ticketBean.getUserAddress(),""),2,0,0,false,false);

        String sendPerson = empty2Default(ticketBean.getSendPersonName(),"") + " " + empty2Default(ticketBean.getSendPersonPhone(),"");
        if (sendPerson.length() > 1){
            lines++;
            zpSDK.drawText(10,total+lineHeight*lines,"发货人："+sendPerson,2,0,0,false,false);
        }

        String sendPersonAddress = empty2Default(ticketBean.getSendPersonAddress(),"");
        if (sendPersonAddress.length() > 0){
            lines++;
            zpSDK.drawText(10,total+lineHeight*lines,"发货地址："+sendPersonAddress,2,0,0,false,false);
        }
        Log.d("vvvvvv", "777777777");
        String deliveryPersonStr = empty2Default(ticketBean.getDeliveryPersonName(),"") + " " + empty2Default(ticketBean.getDeliveryPersonPhone(),"");
        if (deliveryPersonStr.length() > 1){
            lines++;
            zpSDK.drawText(10,total+lineHeight*lines,"配送员："+deliveryPersonStr,2,0,0,false,false);
        }


        total += (lines+1) * lineHeight;
        zpSDK.drawLine(1,0,total,width,total,true);

        int keyPointY = total;

        zpSDK.drawText(10,total+10,"品名："+empty2Default(ticketBean.getProductName(),""),2,0,0,false,false);
        zpSDK.drawText(10+width/3,total+10,"包装："+empty2Default(ticketBean.getPackageName(),""),2,0,0,false,false);
        zpSDK.drawText(10+width*2/3,total+10,"件数："+empty2Default(ticketBean.getNumber(),""),2,0,0,false,false);

        zpSDK.drawText(10,total+54,"重量："+empty2Default(ticketBean.getWeight(),"0")+"kg",2,0,0,false,false);
        zpSDK.drawText(10+width/3,total+54,"保费："+ String.format("%.2f", Float.valueOf(empty2Default(ticketBean.getBaofeiFee(),"0"))),2,0,0,false,false);
        zpSDK.drawText(10+width*2/3,total+54,"运费："+ String.format("%.2f", Float.valueOf(empty2Default(ticketBean.getFreight(),"0"))),2,0,0,false,false);
        zpSDK.drawLine(1,0,total+44,width,total+44,true);
        total +=88;
        zpSDK.drawLine(1,0,total,width,total,true);

        //关键点
        int keyPointY1 = total;
        lineHeight = 44;
        lines = 0;
        Log.d("vvvvvv", "888888888");
        String[] strings = {
                empty2Default(ticketBean.getShengjiaFee(),""),
                empty2Default(ticketBean.getDeliveryFee(),""),
                empty2Default(ticketBean.getLandFee(),""),
                empty2Default(ticketBean.getZhuangxieFee(),""),
                empty2Default(ticketBean.getTransFee(),""),
                empty2Default(ticketBean.getOtherFee(),""),
                empty2Default(ticketBean.getDaidianFee(),""),
                empty2Default(ticketBean.getDaikuanFee(),""),
                empty2Default(ticketBean.getDaishouFee(),""),
                empty2Default(ticketBean.getBaoguanFee(),""),
                empty2Default(ticketBean.getServiceFee(),""),
                empty2Default(ticketBean.getPackageFee(),""),
                empty2Default(ticketBean.getShangloufee(),"")

        };
        Log.d("bbbbb", Arrays.toString(strings));

        String[] titles = {
                "声价：","送货费：","落地费：","装卸费：","垫中转费：",
                "其他费用：","代垫货款：","代款手续费：","代收货款：","报关费：","服务费：","包装费：","上楼费："
        };
        int flag = 0;
        for (int i = 0; i < strings.length; i++) {
            if (!strings[i].equals("")&&strings[i].length() > 0){
                if ((flag+1)%2 == 0){ //抬头
                    zpSDK.drawText(width/2+10,total+lineHeight*lines+10,titles[i]+ String.format("%.2f", Float.valueOf(strings[i])),2,0,0,false,false);
                    zpSDK.drawLine(1,0,total+lineHeight*lines,width,total+lineHeight*lines,true);
                    lines++;
                }else {
                    zpSDK.drawText(10,total+lineHeight*lines+10,titles[i]+ String.format("%.2f", Float.valueOf(strings[i])),2,0,0,false,false);
                }
                flag++;
            }
        }
        if (flag%2==1){
            zpSDK.drawLine(1,0,total+lineHeight*lines,width,total+lineHeight*lines,true);
            lines++;
        }else {
            zpSDK.drawLine(1, 0, total + lineHeight * lines, width, total + lineHeight * lines, true);
        }
        zpSDK.drawText(10,total+lineHeight*lines+10,"回单付："+(ticketBean.isHuidan() ? "是" : "否"),2,0,0,false,false);

        total+=lineHeight*(lines+1);
        zpSDK.drawLine(1,width/2,keyPointY1,width/2,total-lineHeight,true);
        zpSDK.drawLine(1,0,total,width,total,true);
        //画竖线

        zpSDK.drawText(10,total+10,"合计费用："+ String.format("%.2f", Float.valueOf(empty2Default(ticketBean.getTotalFee(),"0"))),2,0,1,false,false);
        zpSDK.drawText(width/2+10,total+10, MoneyUtils.toChinese(empty2Default(ticketBean.getTotalFee(),"0")),2,0,1,false,false);
        zpSDK.drawLine(1,width/2,total,width/2,total+44,true);

        total +=44;

        zpSDK.drawLine(1,0,keyPointY,0,total,true);
        zpSDK.drawLine(1,width,keyPointY,width,total,true);

        zpSDK.drawLine(1,0,total,width,total,true);
        zpSDK.drawText(10,total+10,"备注:",2,0,0,false,false);
        zpSDK.drawText(10 + 72,total+10,empty2Default(ticketBean.getRemarks(),""),2,0,0,false,false);

        total +=44;
        zpSDK.drawLine(1,0,total,width,total,true);

        zpSDK.drawText(10,total+10,width*2/3,30,"运输条款：",2,0,1,false,false);
        zpSDK.drawText(10,total+10+30+10,width*2/3,16*2+5,"① 发货人需要注明货物名称，虚报品名的承运方一律不予保障。",1,0,0,false,false);
        zpSDK.drawText(10,total+10+30+10+42,width*2/3,16*2+5,"② 发货人需要主动购买保险，未购买保险运费三倍给予赔偿，最高不过3000/票。",1,0,0,false,false);
        zpSDK.drawText(10,total+10+30+10+42+42,width*2/3,16*2+5,"③ 当票货一个月内无人认领的，承运无保管责任，均作无效处理",1,0,0,false,false);
        zpSDK.drawText(10,total+10+30+10+42+42+42,width*2/3,16*2+5,"④ 托运危险品和国家违禁物品由发货人承担一切责任",1,0,0,false,false);
        zpSDK.drawQrCode(width*2/3+10,total+20,"http://weixin.qq.com/r/2zmvtyTEW3kkrWDU92zJ",
                0,2,0);
        total += 190;
        zpSDK.drawText(width*2/3+20,total,empty2Default(ticketBean.getTime(),""),1,0,0,false,false);
        total += 100;
        Log.e("total",total+"");
        zpSDK.print(0,0);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                myDisconnect();
//            }
//        },1000L);
        Log.d("vvvvvv", "9999999999");
        zpSDK.disconnect();
        while (zpSDK.isConnected()){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private String empty2Default(String value, String defaultValue){


        Log.d("ccccccccc", "1111111");
        if (value == null || value.length() == 0 ){
            Log.d("ccccccccc", "222222");
            return defaultValue;
        }
        else if (value!=null &&value.equals("0.0")) {
            Log.d("ccccccccc", "3333333");
            return defaultValue;
        }
        return value;
    }

    private int pageHeight(PrintTicketBean bean) {
        int lineHeight = 40;
        String[] strings = {
                empty2Default(bean.getShengjiaFee(), ""),
                empty2Default(bean.getDeliveryFee(), ""),
                empty2Default(bean.getLandFee(), ""),
                empty2Default(bean.getZhuangxieFee(), ""),
                empty2Default(bean.getTransFee(), ""),
                empty2Default(bean.getOtherFee(), ""),
                empty2Default(bean.getDaidianFee(), ""),
                empty2Default(bean.getDaikuanFee(), ""),
                empty2Default(bean.getDaishouFee(), ""),
                empty2Default(bean.getBaoguanFee(), "")
        };
        int flag = 0;
        for (String string : strings) {
            if (string.length() > 0) {
                flag++;
            }
        }

        int subLines = (strings.length / 2 + strings.length % 2) - (flag / 2 + flag % 2);

        String sendPerson = empty2Default(bean.getSendPersonName(), "") + " " + empty2Default(bean.getSendPersonPhone(), "");
        if (sendPerson.length() <= 1) {
            subLines++;
        }

        String sendPersonAddress = empty2Default(bean.getSendPersonAddress(), "");
        if (sendPersonAddress.length() == 0) {
            subLines++;
        }

        String deliveryPersonStr = empty2Default(bean.getDeliveryPersonName(), "") + " " + empty2Default(bean.getDeliveryPersonPhone(), "");
        if (deliveryPersonStr.length() <= 1) {
            subLines++;
        }

        return 1200 - subLines * lineHeight;
    }




//    /**
//     * 调用private修饰的方法getProsenaddress()
//     */
//    public void myDisconnect() {
//        Method method = null;
//        Class temp = zpSDK.getClass();
//        try {
//            method = temp.getDeclaredMethod("SPPClose", null);
//            method.setAccessible(true);
//            method.invoke(zpSDK, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    public String type(Double Gnd) {
        switch (String.valueOf(Gnd)) {
            case "0.0":
                return "%d";
            case "1.0":
                return "%01d";
            case "2.0":
                return "%02d";
            case "3.0":
                return "%03d";
            case "4.0":
                return "%04d";
            default:
                return "%02d";
        }

    }

}
